package com.injurydetection.www;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.injurydetection.www.bean.DataBean;
import com.injurydetection.www.bean.MesEventCount;
import com.injurydetection.www.greendao.DataBeanDao;
import com.injurydetection.www.util.datautil.MakePackage;
import com.injurydetection.www.view.CountDownFragment;
import com.injurydetection.www.view.ExamineFragment;
import com.injurydetection.www.view.ExamineListFragment;

import com.kongqw.serialportlibrary.SerialPortManager;
import com.kongqw.serialportlibrary.listener.OnOpenSerialPortListener;
import com.kongqw.serialportlibrary.listener.OnSerialPortDataListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    int x = R.layout.activity_main;
    @BindView(R.id.examinelist_img)
    ImageView examinelistImg;
    @BindView(R.id.examine_img)
    ImageView examineImg;
    @BindView(R.id.countdown_img)
    ImageView countdownImg;
    @BindView(R.id.fl)
    FrameLayout fl;
    @BindView(R.id.cornertext_tv)
    TextView countTv;
    private ExamineFragment mExamineFragment;
    private ExamineListFragment mExamineListFragment;
    private CountDownFragment mCountDownFragment;
    private FragmentManager mFragmentManager;
    private Unbinder mUnbinder;
    private static final String TAG = "MainActivity";
    private int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestPermission();
        mUnbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        mFragmentManager = getSupportFragmentManager();
        initListener();
        initFragment();
        changeFragment(0);
//        setFullScreen();
        String[] columnNames = {"姓名", "编号", "血型"};
        //excel初始化
//        ExcelUtils.initExcel(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/test.xlsx", "first", columnNames);
//        Log.d(TAG, "路径: " + Environment.getExternalStorageDirectory().getAbsolutePath());

//        openSerialPort();

        final View decorView = getWindow().getDecorView();

        setFullscreen11();


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setCountTest(MesEventCount mesEventCount) {
        countTv.setText(mesEventCount.getCount() + "");
    }

    /**
     * 初始化所有的fragment
     */
    private void initFragment() {
        mExamineFragment = new ExamineFragment();
        mExamineListFragment = new ExamineListFragment();
        mCountDownFragment = new CountDownFragment();
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        examineImg.setOnClickListener(this);
        examinelistImg.setOnClickListener(this);
        countdownImg.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.examine_img:
                changeFragment(0);
                break;
            case R.id.examinelist_img:
                changeFragment(1);
                break;
            case R.id.countdown_img:
                changeFragment(2);
                break;
            default:
                break;
        }
    }

    /**
     * fragment切换
     */
    private void changeFragment(int index) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        switch (index) {
            case 0:
//                List<DataBean> dataBeans = MyApplication.getDaoSession().getDataBeanDao().queryBuilder().where(DataBeanDao.Properties.IsChecked.eq(true)).list();
//                count = dataBeans.size();
                examineImg.setImageResource(R.mipmap.icon_examine22);
                examinelistImg.setImageResource(R.mipmap.icon_examine_list11);
                countdownImg.setImageResource(R.mipmap.icon_countdown_list11);
                transaction.replace(R.id.fl, mExamineFragment, "mExamineFragment");
                transaction.commit();
                break;

            case 1:
//                List<DataBean> dataBeans1 = MyApplication.getDaoSession().getDataBeanDao().queryBuilder().where(DataBeanDao.Properties.IsChecked.eq(true)).list();
//                count = dataBeans1.size();
                examineImg.setImageResource(R.mipmap.icon_examine11);
                examinelistImg.setImageResource(R.mipmap.icon_examine_list22);
                countdownImg.setImageResource(R.mipmap.icon_countdown_list11);
                transaction.replace(R.id.fl, mExamineListFragment, "mExamineListFragment");
                transaction.commit();
                break;
            case 2:
//                List<DataBean> dataBeans2 = MyApplication.getDaoSession().getDataBeanDao().queryBuilder().where(DataBeanDao.Properties.IsChecked.eq(true)).list();
//                count = dataBeans2.size();
                examineImg.setImageResource(R.mipmap.icon_examine11);
                examinelistImg.setImageResource(R.mipmap.icon_examine_list11);
                countdownImg.setImageResource(R.mipmap.icon_countdown_list22);
                transaction.replace(R.id.fl, mCountDownFragment, "mCountDownFragment");
                transaction.commit();
                break;
        }
        //todo
        List<DataBean> dataBeans = MyApplication.getDaoSession().getDataBeanDao().queryBuilder().where(DataBeanDao.Properties.IsChecked.eq(true)).list();
        List<DataBean> tempList = new ArrayList<>();
        for (int i = 0; i < dataBeans.size(); i++) {
            if ((new Date().getTime() - dataBeans.get(i).getCreateTime().getTime()) / 1000 / 60 / 60 <= 5) {
                tempList.add(dataBeans.get(i));
            }
        }
        count = tempList.size();

        countTv.setText(count + "");
    }

    /**
     * 同时隐藏系统的状态栏和导航栏
     */
    @SuppressLint("NewApi")
    private void setFullScreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        if (Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);
        }

        // 全屏展示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // 全屏显示，隐藏状态栏和导航栏，拉出状态栏和导航栏显示一会儿后消失。
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                );
            } else {
                // 全屏显示，隐藏状态栏
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
            }
        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private int REQUEST_PERMISSION_CODE = 1000;

    //请求权限
    private void requestPermission() {
        if (Build.VERSION.SDK_INT > 23) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
                Log.e("权限", "requestPermission:" + "用户之前已经授予了权限！");
            } else {
                requestPermissions(permissions, REQUEST_PERMISSION_CODE);
            }
        }
    }

    private AlertDialog alertDialog;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e("权限", "申请成功");
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("permission");
                builder.setMessage("点击允许才可以使用");
                builder.setPositiveButton("去允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (alertDialog != null && alertDialog.isShowing()) {
                            alertDialog.dismiss();
                        }
                        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                    }
                });
                alertDialog = builder.create();
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
        }
    }

    private void showDialogTipUserRequestPermission() {
        ActivityCompat.requestPermissions(this, permissions, 321);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }

    private void setFullscreen11() {
//        final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
//                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                | View.SYSTEM_UI_FLAG_FULLSCREEN
//                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
//
//        getWindow().getDecorView().setSystemUiVisibility(flags);
        int flags = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_FULLSCREEN |
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        getWindow().getDecorView().setSystemUiVisibility(flags);
        // This code will always hide the navigation bar
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                    getWindow().getDecorView().setSystemUiVisibility(flags);
                }
            }
        });
        getWindow().getDecorView().setSystemUiVisibility(flags);
    }
}
